/*
 * @Author: Turump 
 * @Date: 2021-04-02 09:23:38 
 * @Last Modified by: Turump
 * @Last Modified time: 2021-04-07 19:06:10
 * 触摸播放Animation
 */

import { TaskBase } from "./TaskBase";

const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu("任务组件/触摸播动画")
export default class TouchPlayAnimationTask extends TaskBase {

    @property({ type: cc.Animation, displayName: "动画对象" })
    animation: cc.Animation = null;

    @property({ displayName: "带音效" })
    isMovedWithAudio = true;

    @property({ type: cc.AudioClip, displayName: "动画播放时的音效", visible() { return this.isMovedWithAudio } })
    movingAudio: cc.AudioClip = null;

    _animationClip: cc.AnimationClip = null;
    _moveAudioId = -1

    onLoad() {
        super.onLoad();
        this._animationClip = this.animation.getClips()[0]

        this.animation.on("finished", this.animationPlayFinished, this)
    }

    enableTask() {
        super.enableTask();
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchBegined, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.touchEnded, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.touchEnded, this);
    }

    stopTask() {
        super.stopTask();
        this.animationPlayFinished();
        this.animation.stop();
    }

    animationPlayFinished() {
        this.stopPlayAudio();
        this.node.off(cc.Node.EventType.TOUCH_START, this.touchBegined, this);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this.touchEnded, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this.touchEnded, this);
        this.emitDoneEvent();
    }

    //绘制的上一个点
    touchBegined(event: cc.Event.EventTouch) {
        if (this.animation.getAnimationState(this._animationClip.name).isPaused) {
            this.animation.resume(this._animationClip.name)
        } else {
            this.animation.play(this._animationClip.name)
        }
        if (this.movingAudio != null)
            this._moveAudioId = cc.audioEngine.playEffect(this.movingAudio, true);
    }


    touchEnded(event: cc.Event.EventTouch) {
        this.animation.pause(this._animationClip.name);
        this.stopPlayAudio();
    }

    stopPlayAudio() {
        cc.audioEngine.stopEffect(this._moveAudioId);
        this._moveAudioId = -1;
    }

}
